
import { useTranslation } from 'react-i18next'
import { Link, useNavigate } from "react-router-dom";
import HeaderTitle from "./header";
import style from "./index.module.less"
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons"
import React, { Fragment, useState,useEffect } from 'react'
import {
	Form,
	Input,
	Checkbox,
	Button,
	Toast,

} from 'antd-mobile'
import { login,getsysconfig } from "@/apis/user.js"

import logo from '../../static/Q9.png'

const TIME = 60000; //定义时效性


const Login = (props) => {
	const { t, i18n } = useTranslation();
	const BASE_URL = import.meta.env.VITE_BASE_URL;
	const navigate = useNavigate()
	const [visible, setVisible] = useState(false)
	const [formData, setFormData] = useState({ name: '', password: '', checked: false })
	const [form] = Form.useForm()
	const [sitelogo,setsitelogo] = useState('')
	// 查看缓存中是否有账号密码
	// let formDataMemo = {}
	// if(localStorage.getItem('formData')){
	// 	formDataMemo = JSON.parse(localStorage.getItem('formData'))
	// }
	// if (formDataMemo.name && formDataMemo.password && formDataMemo.expirationTime && Date.now() < formDataMemo.expirationTime) {
	// 	setFormData({
	// 		name: formDataMemo.name,
	// 		password: formDataMemo.password,
	// 		checked: true,
	// 	})

	// 	console.log(formData, 'formData')
	// }
	
	useEffect(() => {
		// setFlag(true);
		if(!localStorage.getItem('lang')){
			localStorage.setItem('lang', 'hk')
			localStorage.setItem('langs','0')
		}
		i18n.changeLanguage(localStorage.getItem('lang'))
		getsysconfig().then(res => {
			if (res.status.errorCode == 0) {
				localStorage.setItem("config",JSON.stringify(res.data))
				setsitelogo(res.data.site_logo)
			}
		})
		if(localStorage.getItem('config')){
			setsitelogo(JSON.parse(localStorage.getItem('config')).site_logo || '')
		}
		
		if(localStorage.getItem('formData')){
			let formDataMemo = JSON.parse(localStorage.getItem('formData'))
			console.log(formDataMemo,9999)
			setFormData({
				name: formDataMemo.name,
				password: formDataMemo.password,
				checked:formDataMemo.checked
			})
			console.log(formData)
			form.setFieldValue("name", formDataMemo.name);
			form.setFieldValue("password", formDataMemo.password);
		}
		setTimeout(()=>{
			if (window.scrollTo) {		  
				window.scrollTo(0, 0);
			} else if (document.body.scrollTop) {
				document.body.scrollTop = 0;
			} else {
				document.documentElement.scrollTop = 0;
			}
				document.getElementById('root').scrollIntoView(true);
				document.getElementById('body').scrollIntoView(true);
		},0)
		return ()=>{console.log('初始化----登录')}
	  }, []);
	
	const onFinish = (values) => {
		Toast.show({
			icon: 'loading',
			content: t('login.title51'),//'加载中'
			
		  })
		/*
			1.调用登录接口
			2.登录成功之后，看其是否勾选了记住密码，如果记住密码则将账号密码缓存在内存中
			3.下次进入秘密
		*/
		login(values).then(res => {
			if (res.status.errorCode == 0) {
				localStorage.setItem('login',1)
				localStorage.setItem('token',res.data)
				Toast.show({
					icon: 'success',
					content: res.status.msg,
				})
				navigate('/index')
				// 如果设置了记住密码，则在登录后将账号密码存储在cookie或storage中，并设置时效性以此来记住密码
				if (formData.checked) {
					localStorage.setItem('formData', JSON.stringify({
						...values,
						expirationTime: Date.now() + TIME,
						checked:true
					}));
					localStorage.setItem('token',res.data)
				} else {
					localStorage.removeItem('formData')
				}
			} else {
				Toast.show({
					icon: 'fail',
					content: res.status.msg,
				})

			}
		})

	};

	const onFinishFailed = (errorInfo) => {
		console.log('Failed:', errorInfo);
	};
	const pagego = (link)=>{
		window.open(JSON.parse(localStorage.getItem("config"))[link])
	}



	return (
		<React.Fragment>
			<HeaderTitle title={t('login.title1')} link="1"/>
			<div className={style['login_box']}>
				<div style={{ textAlign: 'center' }}>
					<img src={logo} alt=""  className={style['img10']} />
				</div>
				<Form
					form={form}
					layout='horizontal'
					onFinish={onFinish}
					initialValues={formData}
				>
					<Form.Item
						
						label={t('login.title2')}
						name='name'
						defaulValue={formData.name}
						rules={[{ required: true, message:t('login.title3') }, 
						{ pattern: /^(?=\w*\d)(?=\w*[a-zA-Z])[\w]{6,12}$/, message: t('login.title4') }]}
					>
						<Input placeholder={t('login.title5')} />
					</Form.Item>
					<Form.Item
						
						label={t('login.title6')}
						name='password'
						defaulValue={formData.password}
						rules={[{ required: true, message:t('login.title7') }]}
						extra={
							<div>
								{!visible ? (
									<EyeInvisibleOutline onClick={() => setVisible(true)} />
								) : (
									<EyeOutline onClick={() => setVisible(false)} />
								)}
							</div>
						}>
						<Input placeholder={t('login.title8')} type={visible ? 'text' : 'password'} />
					</Form.Item>

				</Form>
				<div className={style['operation']}>
					<span>
						<Checkbox onChange={e => setFormData({ ...formData, checked:e })} checked={formData.checked} defaultChecked={formData.checked} >
							{t('login.title9')}
						</Checkbox>
					</span>
					<span onClick={()=>{pagego('app_link')}}>{t('login.title10')}</span>
				</div>
				<React.Fragment>
					<Button shape='rounded' className={style['btns']} style={{ marginBottom: '15px', marginTop: '15px' }} block onClick={() => {
						console.log(form, 'fomr')
						form.validateFields()
						form.submit()
					}} color='primary'>
						{t('login.title11')}
					</Button>
					<Button shape='rounded' className={style['btns']} block type='submit' color='primary' onClick={() => navigate('/register')}>
						{t('login.title12')}
					</Button>
					<p className={style['other-info']} onClick={() => navigate('/index')}>{t('login.title13')}</p>

				</React.Fragment>
			</div>
		</React.Fragment>

	)
}


export default Login
